package com.jiwei.community.controller;

import com.jiwei.community.entity.User;
import com.jiwei.community.exception.SystemException;
import com.jiwei.community.service.LoginService;
import com.jiwei.community.utils.RedisCache;
import com.jiwei.community.utils.SecurityUtils;
import com.jiwei.community.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 季伟
 * @date 2024/3/15
 */
@RestController
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    RedisCache redisCache;
    @RequestMapping("/login")
    public ResponseResult login(@RequestBody User user){
        return loginService.login(user);
    }
    @RequestMapping("/register")
    public ResponseResult register(@RequestBody User user){
        user.setType(0);
        return loginService.register(user);
    }

//    @GetMapping("/isLogin")
//    public ResponseResult isLogin(String userName){
//        return loginService.isLogin(userName);
//    }
    @GetMapping("/isLogin")
    public ResponseResult isLogin(){
        Map<String,Object> map = new HashMap<>();
        Long userId = null;
        try{
            userId = SecurityUtils.getUserId();
        }catch (SystemException e){
        }
        if (userId == null){
            map.put("isLogin",false);
        }else {
            map.put("isLogin",true);
            redisCache.expire("login:"+userId,3, TimeUnit.HOURS);
        }
        return ResponseResult.okResult(map);
    }

    @RequestMapping("/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }


    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode("root"));
        System.out.println(passwordEncoder.matches("kiyato","$2a$10$WD.8q2dGcX71On3WgfzUjOw3X4ltcmlf5ZcXemMOsb6hlh0oL5YjG"));
    }
}
